var express = require('express')
var path = require('path')
var cookieParser = require('cookie-parser')
var logger = require('morgan')

const { jwtAuth } = require('./utils/user-jwt')
var cors = require('cors')

var indexRouter = require('./routes/index')
var usersRouter = require('./routes/users')
var loginRouter = require('./routes/login')
var eventRouter = require('./routes/event')
var noticeRouter = require('./routes/notice')
var registerRouter = require('./routes/register')
var app = express()
app.use(cors())
app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

app.use('/', indexRouter)
app.use('/users', usersRouter)
app.use('/login', loginRouter)
app.use('/event', eventRouter)
app.use('/notice', noticeRouter)
app.use('/register', registerRouter)
//全局验证,如果token过期,提示错误
app.use(jwtAuth, (err, req, res, next) => {
  // 判断是否由 Token 解析失败导致的
  if (err.name == 'UnauthorizedError') {
    return res.send({
      status: 401,
      message: '登录凭证失效,请重新登录!',
    })
  }
  res.send({
    status: 500,
    message: '未知的错误!',
  })
})

module.exports = app
